/**
 * 
 */
package com.xb.cloud.merchantapi.adapter;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.xb.cloud.common.util.SimpleUploadUtils;
import com.xb.cloud.gateway.client.Adapter;
import com.xb.cloud.gateway.client.AdapterContext;
import com.xb.cloud.gateway.client.ReturnCodes;
import com.xb.cloud.gateway.client.ReturnUtils;
import com.xb.cloud.gateway.client.RtnInfo;

/**
 * 通用的文件、图片上传
 * 
 * @author kexue
 *
 */
@Component
public class UploadAdpater extends Adapter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(UploadAdpater.class);

	/**
	 * 上传
	 */
	private RtnInfo doUpload(AdapterContext context) {

		try {
			// 解析请求的内容提取文件数据
			List<FileItem> formItems = context.getRequestInfo().getFileItems();

			if (formItems != null && formItems.size() > 0) {
				// 迭代表单数据
				for (FileItem item : formItems) {
					// 处理不在表单中的字段
					if (!item.isFormField()) {
						String url = SimpleUploadUtils.uploadUUIDName(item.getName(), item.getInputStream());
						if (url != null && !url.isEmpty()) {
							logger.info("文件上传成功:" + item.getFieldName());
							return ReturnUtils.success(url);
						} else {
							logger.error("文件上传失败:" + item.getFieldName());
							ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error("文件上传失败:");
			ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
		}

		return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
	}

	/**
	 * TODO 上传前的文件检查，权限检查
	 */
	@Override
	public RtnInfo execute(String urlPath, Boolean isLogined, Map<String, String> bizInfo, AdapterContext context) {
		return doUpload(context);
	}

	@Override
	public String getUrlMappingPath() {
		return "/h5/upload";
	}

	@Override
	public boolean isCheckUserToken() {
		return true;
	}
}
